<?php

use Phalcon\Mvc\Controller;

class ControllerBase extends Controller
{
     protected $return_data = array();
     public $user_info=array();
     public $params = array();
     public $user_admin =[];
    protected function initialize()
    {
//        header("Access-Control-Allow-Origin:*");
//        header('Access-Control-Allow-Methods:POST');
//        header('Access-Control-Allow-Headers:x-requested-with, content-type');
//        header('Content-Type:application/json');

        header("Access-Control-Allow-Origin:*");
        header("Access-Control-Allow-Credentials:true");
        header("Access-Control-Allow-Methods:*");
        header("Access-Control-Allow-Headers:authorization,content-type");
        try {
            $token = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : '';
            $authorizationInfo = explode(":", openssl_decrypt(base64_decode($token), 'DES-EDE3', ToolsController::KEY, OPENSSL_RAW_DATA));
            $user_token['id'] = isset($authorizationInfo[0]) ? $authorizationInfo[0] : 0;
            $user_token['token'] = isset($authorizationInfo[1]) ? $authorizationInfo[1] : '';
            $this->user_admin = self::certification($user_token);
            $this->params=array_merge($this->request->get(),$this->request->getPost());
            $params = file_get_contents('php://input');
            if($params){
                $params = json_decode($params,true);
                $this->params = array_merge($this->params,$params);
            }
        }catch (Exception $e){
            $this->fail(10001,'非法授权');
        }
        $this->config=new \Phalcon\Config\Adapter\Ini("../app/config/config.ini");

    }



    /**
     * 获取用户信息后 验证Token
     * @return mixed
     */
    private function certification($data = []){
        if (!$data['token'])
            $this->fail(10001,'请先登录');
        $admin_token = new AdminUserToken();
        $token_user = $admin_token->find_by_firstToken($data['token']);
        if ($token_user['expiretime'] < date('Y-m-d H:i:s',time()))
            $this->fail(10001,'登录凭证已失效，请重新登录');
        if ($token_user['admin_id'] !== $data['id'])
            $this->fail(10001,'非法登录');
        $adminusers = new Adminusers();
        $has = $adminusers->find_by_firstId($data['id']);
        if(empty($has))
            $this->fail(10001,'该用户已经失效');
        if($has['status'] == 2)
            $this->fail(10001,'改用户以冻结');
        return $has;
    }


	public function ok($data = null,$code=20000,$msg='操作成功')
	{
		$this->return_data['code']=$code;
        $this->return_data['data']=$data;
        $this->return_data['msg']=$msg;
        echo json_encode($this->return_data,1);
        exit();
	}

	public function fail($code=0,$msg)
    {
        $this->return_data['code']=$code;
        $this->return_data['msg']=$msg;
        echo json_encode($this->return_data,1);
        exit();
    }


}
